package com.fort.teachermanagementsys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fort.teachermanagementsys.entity.SysRole;
import com.fort.teachermanagementsys.entity.SysUserRole;
import com.fort.teachermanagementsys.entity.User;
import com.fort.teachermanagementsys.mapper.SysRoleMapper;
import com.fort.teachermanagementsys.mapper.SysUserRoleMapper;
import com.fort.teachermanagementsys.mapper.UserMapper;
import com.fort.teachermanagementsys.service.UserService;
import com.fort.teachermanagementsys.springsecurity.entity.SelfUserEntity;
import com.fort.teachermanagementsys.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {




    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Result register(String username, String password) {
        try {
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
            User user = userMapper.selectOne(queryWrapper.eq(User::getUsername,username));
            if(user != null){
                return null;
            }else {
                User user1 = new User();
                user1.setUsername(username);
                user1.setCreateTime(LocalDateTime.now());
                user1.setUpdateTime(LocalDateTime.now());
                user1.setCreateBy("FC");
                user1.setPassword(new BCryptPasswordEncoder().encode(password));
                userMapper.insert(user1);
                return Result.success(user1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.failed("注册失败！");
    }

    @Override
    public User getUserByUsername(String username,String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public List<SysRole> getAuthorities(String username) {
        User user = baseMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return roleMapper.getAuthories(user.getId());
    }


    @Override
    public List<User> getAllUsers() {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        List<User> users = userMapper.selectList(queryWrapper);
        return users;
    }

    @Override
    public Result updatePassword(String oldPassword,String password,String rePassword, Authentication authentication) {
        //todo

        try {
            SelfUserEntity selfUserEntity = (SelfUserEntity) authentication.getPrincipal();
            Integer id = selfUserEntity.getId();
            LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(User::getId,id);
            User user = userMapper.selectOne(queryWrapper);
            if(user == null){
                return Result.failed("用户不存在");
            }
            String pr = user.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (!passwordEncoder.matches(oldPassword,pr)){
                return Result.failed("旧密码输入错误");
            }
            if (!password.equals(rePassword)){
                return Result.failed("确认密码输入错误");
            }
            userMapper.updatePassword(new BCryptPasswordEncoder().encode(password), id);
            return Result.success("修改密码成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.failed();
    }

    // 删除用户
    @Transactional
    public void deleteUser(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null || !"0".equals(user.getDelFlag())) {
            throw new RuntimeException("用户不存在");
        }
        user.setDelFlag("1");
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        // 删除关联的角色
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        sysUserRoleMapper.delete(wrapper);
    }

    // 分配角色
    @Transactional
    public void assignRoles(Integer userId, List<Integer> roleIds) {
        // 删除旧的角色关联
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        sysUserRoleMapper.delete(wrapper);
        // 插入新的角色关联
        for (Integer roleId : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            sysUserRoleMapper.insert(userRole);
        }
    }

    // 查询用户关联的角色 ID
    public List<Integer> getRoleIdsByUserId(Integer userId) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return sysUserRoleMapper.selectList(wrapper).stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    // 根据 ID 查询用户
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }
}
